import pyinotify
import os


class OnLinux(pyinotify.ProcessEvent):
    
    def __init__(self,notipy):
        self.notipy = notipy
        
    
    def process_IN_CREATE(self,event):
        if os.path.isdir(event.pathname):
            self.notipy.event_dir_new(event.pathname)
        else:
            self.notipy.event_file_new(event.pathname)
        
    def process_IN_DELETE(self,event):
        if os.path.isdir(event.pathname):
            self.notipy.event_dir_deleted(event.pathname)
        else:
            self.notipy.event_file_deleted(event.pathname)
    
    def process_IN_MODIFY(self,event):
        if os.path.isdir(event.pathname):
            self.notipy.event_dir_modified(event.pathname)
        else:
            self.notipy.event_file_modified(event.pathname)
    
    
    def process_IN_MOVED_FROM(self,event):
        self._movedfrom = event.pathname
    
    def process_IN_MOVED_TO(self,event):
        movedfrom = self._movedfrom
        if os.path.isdir(event.pathname):
            self.notipy.event_dir_moved(movedfrom,event.pathname)
        else:
            self.notipy.event_file_moved(movedfrom,event.pathname)
        del(self._movedfrom)

        
def StartWatching(notipy,dir):
    wm = pyinotify.WatchManager()
    mask = pyinotify.IN_MODIFY | pyinotify.IN_DELETE | pyinotify.IN_CREATE | pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO
    handler = OnLinux(notipy)
    wdd = wm.add_watch(dir, mask, rec=True)
    notifier = pyinotify.Notifier(wm,handler)
    notifier.loop()